import Icon from '@/components/Icon'
import Input from '@/components/Input'
import NavBar from '@/components/NavBar'
import { getUser } from '@/store/actions/profile'
import { useEffect, useRef, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import styles from './index.module.scss'
import io from 'socket.io-client'
import { baseLink } from '@/utils/request'

const Chat = () => {
  const user = useSelector((state) => state.profile.user)
  const token = useSelector((state) => state.login.token)
  const [msg, setMsg] = useState('')
  const [list, setList] = useState([])
  const dispatch = useDispatch()
  const clientRef = useRef(null)
  const chatRef = useRef(null)

  // 一进页面, 拉取个人信息的数据
  useEffect(() => {
    dispatch(getUser())
  }, [dispatch])

  // 一进页面, 建立websoket连接
  useEffect(() => {
    // 1. 建立连接
    const client = io(baseLink, {
      query: {
        token,
      },
      transports: ['websocket'],
    })
    // 将client存入ref
    clientRef.current = client

    // 2. 监听连接的建立 connect
    client.on('connect', () => {
      console.log('恭喜, 连接建立成功')
      // 基于当前的最新的list, 往后面追加一个数据
      setList((list) => [
        ...list,
        { type: 'robot', text: '亲爱的用户您好，小智同学为您服务。' },
      ])
    })

    // 3. 监听消息推送
    client.on('message', (data) => {
      setList((list) => [...list, { type: 'robot', text: data.msg }])
    })

    // 当组件销毁时, 或者再次执行useEffect前, 执行
    return () => {
      // 断开连接, 清除副作用的影响
      console.log('连接断开')
      client.close()
    }
  }, [token])

  // 只要list变化了，就会按照最新的高度进行滚动设置
  useEffect(() => {
    chatRef.current.scrollTop = chatRef.current.scrollHeight
  }, [list])

  const handleKeyUp = (e) => {
    if (e.keyCode === 13) {
      // 回车发送
      // 1. 在页面中, 追加一条我说
      setList((list) => [...list, { type: 'user', text: msg }])
      // 2. 将消息, 发送给后台
      clientRef.current.emit('message', {
        msg: msg,
        timestamp: +new Date(),
      })
      // 清空文本框
      setMsg('')
    }
  }

  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar className="fixed-header">小智同学</NavBar>

      {/* 聊天记录列表 */}
      <div className="chat-list" ref={chatRef}>
        {list.map((item, index) => {
          if (item.type === 'robot') {
            return (
              <div key={index} className="chat-item ">
                <Icon type="iconbtn_xiaozhitongxue" />
                <div className="message">{item.text}</div>
              </div>
            )
          } else {
            return (
              <div key={index} className="chat-item user">
                <img
                  src={
                    user.photo ||
                    'http://toutiao.itheima.net/images/user_head.jpg'
                  }
                  alt=""
                />
                <div className="message">{item.text}</div>
              </div>
            )
          }
        })}
      </div>

      {/* 底部消息输入框 */}
      <div className="input-footer">
        <Input
          value={msg}
          onChange={(e) => setMsg(e.target.value)}
          className="no-border"
          placeholder="请描述您的问题"
          onKeyUp={handleKeyUp}
        />
        <Icon type="iconbianji" />
      </div>
    </div>
  )
}

export default Chat
